package com.kangjia.model.m3.controller;

import java.io.Serializable;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kangjia.general.controller.AbstractController;
import com.kangjia.general.dao.query.OperType;
import com.kangjia.general.dao.query.Page;
import com.kangjia.general.dao.query.Param;
import com.kangjia.general.dao.query.QueryParam;
import com.kangjia.jasckson.DataMapper;
import com.kangjia.model.m3.entity.Product;
import com.kangjia.response.AbstractResponse;
import com.kangjia.response.ObjectResponse;
import com.kangjia.response.SuccessResponse;

@Controller
@RequestMapping(value = "/b/index/product", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class ProductController extends AbstractController<Product> {

	private static final String PRODUCT_CODE = "product.code";

	@RequestMapping(value = "/editor")
	@ResponseBody
	public AbstractResponse editor(@RequestBody Product product) {
		Long productId = product.getProductId();
		if (productId == null) {
			Long inc = hinc(HW_INC_KEY, PRODUCT_CODE);
			product.setProductCode(String.format("%09d", inc));
		}
		ObjectResponse<Product> response = super.editorx(product);
		hset("indexType_" + product.getIndexTypeId(), product.getProductId().toString(), DataMapper.write(response.getData()));
		return new SuccessResponse("操作成功");
	}

	@RequestMapping(value = "/delete")
	@ResponseBody
	public AbstractResponse delete(@RequestBody Product product) {
		hdel("indexType_" + product.getIndexTypeId(), product.getProductId().toString());
		return super.deleteById(product.getProductId(), null);
	}

	@RequestMapping(value = "/find")
	@ResponseBody
	public AbstractResponse find(@RequestBody Product product) {
		return super.find(product.getProductId(), null);
	}

	@RequestMapping(value = "/search")
	@ResponseBody
	public AbstractResponse tree(@RequestBody Product product) {
		Page page = new Page();
		page.setStart(product.getStart());
		page.setLimit(product.getLimit());
		QueryParam param = new QueryParam(page);
		param.addParam(new Param<Long>("indexTypeId", OperType.eq, product.getIndexTypeId()));
		return super.query(param, null);
	}

	public Serializable getPrimary(Product entity) {
		return entity.getProductId();
	}

	public Class<Product> getClazz() {
		return Product.class;
	}

	public void status(Product entity) {

	}

	public String[] ignores() {
		return new String[] { "productCode" };
	}
}
